
<template>
  <div class="asset-disposal">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>资产减档</span>
          <el-button type="primary" @click="handleAddDisposal">发起减档申请</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="申请单号">
          <el-input v-model="searchForm.applicationNo" placeholder="请输入申请单号" clearable />
        </el-form-item>
        <el-form-item label="资产名称">
          <el-input v-model="searchForm.assetName" placeholder="请输入资产名称" clearable />
        </el-form-item>
        <el-form-item label="资产分类">
          <el-select v-model="searchForm.category" placeholder="请选择资产分类" clearable>
            <el-option label="固定资产" value="fixed" />
            <el-option label="低值易耗品" value="low_value" />
            <el-option label="租赁资产" value="lease" />
            <el-option label="租入固定资产改良" value="lease_improvement" />
          </el-select>
        </el-form-item>
        <el-form-item label="减档类型">
          <el-select v-model="searchForm.disposalType" placeholder="请选择减档类型" clearable>
            <el-option label="报废" value="scrap" />
            <el-option label="处置" value="disposal" />
            <el-option label="减账" value="write_off" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请状态">
          <el-select v-model="searchForm.status" placeholder="请选择申请状态" clearable>
            <el-option label="待审批" value="pending" />
            <el-option label="审批中" value="approving" />
            <el-option label="已批准" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="applicationNo" label="申请单号" width="150" />
        <el-table-column prop="assetName" label="资产名称" width="180" />
        <el-table-column prop="assetCode" label="资产编码" width="120" />
        <el-table-column prop="category" label="资产分类" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">
              {{ getCategoryLabel(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="disposalType" label="减档类型" width="100">
          <template #default="scope">
            <el-tag :type="getDisposalType(scope.row.disposalType)">
              {{ getDisposalTypeLabel(scope.row.disposalType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyDate" label="申请日期" width="120" />
        <el-table-column prop="applicant" label="申请人" width="120" />
        <el-table-column prop="status" label="申请状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
            <el-button 
              v-if="scope.row.status === 'pending'" 
              link type="primary" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="scope.row.status === 'completed'" 
              link type="primary" 
              @click="handlePrint(scope.row)"
            >
              打印审批表
            </el-button>
            <el-button 
              v-if="scope.row.status === 'pending'" 
              link type="danger" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发起减档申请对话框 -->
    <el-dialog
      v-model="disposalDialogVisible"
      title="发起资产减档申请"
      width="600px"
    >
      <el-form
        ref="disposalFormRef"
        :model="disposalForm"
        :rules="disposalRules"
        label-width="120px"
      >
        <el-form-item label="选择资产" prop="assetId">
          <el-select v-model="disposalForm.assetId" placeholder="请选择资产" style="width: 100%">
            <el-option
              v-for="asset in assetOptions"
              :key="asset.id"
              :label="`${asset.name} (${asset.code})`"
              :value="asset.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="减档类型" prop="disposalType">
          <el-radio-group v-model="disposalForm.disposalType">
            <el-radio label="scrap">报废</el-radio>
            <el-radio label="disposal">处置</el-radio>
            <el-radio label="write_off" v-if="disposalForm.category === 'lease_improvement'">减账</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="减档原因" prop="reason">
          <el-select v-model="disposalForm.reason" placeholder="请选择减档原因" style="width: 100%">
            <el-option label="达到使用年限" value="lifespan" />
            <el-option label="严重损坏无法修复" value="damaged" />
            <el-option label="技术落后被淘汰" value="obsolete" />
            <el-option label="其他原因" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="减档日期" prop="disposalDate">
          <el-date-picker
            v-model="disposalForm.disposalDate"
            type="date"
            placeholder="请选择减档日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="减档说明" prop="description">
          <el-input
            v-model="disposalForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入减档说明"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            :on-remove="handleRemove"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png/pdf文件，且不超过5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="disposalDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDisposalForm">提交申请</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  applicationNo: '',
  assetName: '',
  category: '',
  disposalType: '',
  status: ''
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    applicationNo: 'JZ20230001',
    assetId: 1,
    assetName: '笔记本电脑',
    assetCode: 'ZC20230001',
    category: 'fixed',
    disposalType: 'scrap',
    applyDate: '2023-11-15',
    applicant: '张三',
    status: 'pending',
    reason: '严重损坏无法修复',
    description: '笔记本电脑因进水严重损坏，无法修复，申请报废处理'
  },
  {
    id: 2,
    applicationNo: 'JZ20230002',
    assetId: 2,
    assetName: '办公桌',
    assetCode: 'ZC20230002',
    category: 'low_value',
    disposalType: 'disposal',
    applyDate: '2023-11-10',
    applicant: '李四',
    status: 'completed',
    reason: '达到使用年限',
    description: '办公桌已使用超过8年，达到使用年限，申请处置'
  }
])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
})

// 资产选项
const assetOptions = ref([
  {
    id: 1,
    name: '笔记本电脑',
    code: 'ZC20230001',
    category: 'fixed'
  },
  {
    id: 2,
    name: '办公桌',
    code: 'ZC20230002',
    category: 'low_value'
  }
])

// 发起减档申请相关
const disposalFormRef = ref()
const disposalDialogVisible = ref(false)
const fileList = ref([])
const disposalForm = reactive({
  assetId: '',
  category: '',
  disposalType: 'scrap',
  reason: '',
  disposalDate: '',
  description: ''
})

const disposalRules = reactive({
  assetId: [
    { required: true, message: '请选择资产', trigger: 'change' }
  ],
  disposalType: [
    { required: true, message: '请选择减档类型', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请选择减档原因', trigger: 'change' }
  ],
  disposalDate: [
    { required: true, message: '请选择减档日期', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入减档说明', trigger: 'blur' }
  ]
})

// 监听资产选择变化，自动填充资产分类
watch(() => disposalForm.assetId, (newVal) => {
  if (newVal) {
    const asset = assetOptions.value.find(item => item.id === newVal)
    if (asset) {
      disposalForm.category = asset.category
      // 如果是租入固定资产改良，默认选择减账
      if (asset.category === 'lease_improvement') {
        disposalForm.disposalType = 'write_off'
      } else {
        disposalForm.disposalType = 'scrap'
      }
    }
  } else {
    disposalForm.category = ''
  }
})

// 获取资产分类标签
const getCategoryLabel = (category) => {
  const categoryMap = {
    fixed: '固定资产',
    low_value: '低值易耗品',
    lease: '租赁资产',
    lease_improvement: '租入固定资产改良'
  }
  return categoryMap[category] || category
}

// 获取资产分类类型
const getCategoryType = (category) => {
  const typeMap = {
    fixed: '',
    low_value: 'success',
    lease: 'warning',
    lease_improvement: 'info'
  }
  return typeMap[category] || ''
}

// 获取减档类型标签
const getDisposalTypeLabel = (disposalType) => {
  const typeMap = {
    scrap: '报废',
    disposal: '处置',
    write_off: '减账'
  }
  return typeMap[disposalType] || disposalType
}

// 获取减档类型样式
const getDisposalType = (disposalType) => {
  const typeMap = {
    scrap: 'danger',
    disposal: 'warning',
    write_off: 'info'
  }
  return typeMap[disposalType] || ''
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    pending: '待审批',
    approving: '审批中',
    approved: '已批准',
    rejected: '已拒绝',
    completed: '已完成'
  }
  return statusMap[status] || status
}

// 获取状态样式
const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    approving: 'primary',
    approved: 'success',
    rejected: 'danger',
    completed: 'info'
  }
  return typeMap[status] || ''
}

// 搜索
const handleSearch = () => {
  console.log('搜索条件：', searchForm)
  ElMessage.success('搜索成功')
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  ElMessage.success('重置成功')
}

// 发起减档申请
const handleAddDisposal = () => {
  // 重置表单
  Object.keys(disposalForm).forEach(key => {
    if (key === 'disposalType') {
      disposalForm[key] = 'scrap'
    } else {
      disposalForm[key] = ''
    }
  })
  fileList.value = []
  disposalDialogVisible.value = true
}

// 文件变化
const handleFileChange = (file, fileList) => {
  console.log(file, fileList)
}

// 移除文件
const handleRemove = (file, fileList) => {
  console.log(file, fileList)
}

// 提交减档申请表单
const submitDisposalForm = () => {
  disposalFormRef.value.validate((valid) => {
    if (valid) {
      // 实际应该调用API保存数据
      console.log('减档申请表单数据：', disposalForm)
      ElMessage.success('提交成功')
      disposalDialogVisible.value = false
    }
  })
}

// 查看申请详情
const handleView = (row) => {
  router.push(`/asset-disposal/apply/${row.id}`)
}

// 编辑申请
const handleEdit = (row) => {
  router.push(`/asset-disposal/apply/${row.id}`)
}

// 打印审批表
const handlePrint = (row) => {
  ElMessage.success(`正在打印申请单 ${row.applicationNo} 的审批表...`)
  // 实际应该调用打印功能
}

// 删除申请
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除减档申请 "${row.applicationNo}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应该调用API删除
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  // 实际应该重新加载数据
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  // 实际应该重新加载数据
}
</script>

<style scoped>
.asset-disposal {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
